<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginData" :rules="loginRules" class="login-form" autocomplete="on" label-position="left" v-if="loginFlag">

      <div class="title-container">
        <h3 class="title">更多客PMS</h3>
      </div>

      <el-form-item prop="username" :error="loginErrMsg">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginData.username" @focus="loginErrMsg=''" placeholder="用户名" name="username" type="text" tabindex="1" autocomplete="on" />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="大写锁定打开" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input :key="passwordType" ref="password" v-model="loginData.password"
                    :type="passwordType" placeholder="密码" name="password"
                    tabindex="2" autocomplete="on"
                    @keyup.native="checkCapslock" @blur="capsTooltip = false"
                    @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>
      <!-- <el-button  type="primary" style="width:49%;margin-bottom:30px;margin-left:0px" @click.native.prevent="handleDingLogin">钉钉登录</el-button> -->
      <!-- <el-button  type="primary" style="width:49%;margin-bottom:30px;margin-left:8px" @click.native.prevent="handleWxLogin">微信登录</el-button> -->
      <!-- <el-button  type="primary" style="width:49%;margin-bottom:30px;margin-left:8px" @click.native.prevent="handlePhone">获取验证码</el-button> -->

    </el-form>
    <el-form ref="dingLoginForm"  class="login-form" autocomplete="on" label-position="left" v-show="dingLoginFlag">
        <div id="login_container">

        </div>
        <el-button  type="primary" style="width:100%;margin-bottom:30px;margin-left:0px" @click.native.prevent="handleBackLogin">返回登录</el-button>
    </el-form>
     <el-form ref="wxLoginForm"  class="login-form" autocomplete="on" label-position="left" v-show="wxLoginFlag">
        <div id="wxLogin_container" style="text-align:center">

        </div>
        <div id="promptBox"></div>
        <el-button  type="primary" style="width:100%;margin-bottom:30px;margin-left:0px" @click.native.prevent="handleBackLogin">返回登录</el-button>
    </el-form>

    <el-form ref="phoneForm"  class="login-form" autocomplete="on" label-position="left" v-show="phoneFlag" :rules="phoneRules" :model="phoneLoginData">
      <el-form-item prop="phone">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="phone" v-model="phoneLoginData.phone" maxlength="11" placeholder="手机号" name="phone" type="text" tabindex="1" autocomplete="on" />
      </el-form-item>
      <el-form-item prop="phoneCode" >
        <!-- <div class="verify-wrapper">
          <el-input ref="phoneCode" v-model="phoneLoginData.phoneCode"  placeholder="验证码" name="phoneCode" type="text" tabindex="1" autocomplete="on" />
          <el-button :disabled="disabled" @click="getCode">{{valiBtn}}</el-button>
        </div> -->

        <el-col :span="15">
          <el-input ref="phoneCode" v-model="phoneLoginData.phoneCode"  placeholder="验证码" name="phoneCode" type="text" tabindex="1" autocomplete="on" style="width: 100%;"/>

        </el-col>
         <el-col :span="8">
                    <el-button :disabled="disabled" @click="getCode" style="width: 100%;line-height:20px">{{valiBtn}}</el-button>

        </el-col>

      </el-form-item>
       <el-button :loading="phoneLoading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handlePhoneLogin">登录</el-button>
      <el-button  type="primary" style="width:100%;margin-bottom:30px;margin-left:0px" @click.native.prevent="handleBackLogin">返回登录</el-button>
    </el-form>

  </div>
</template>

<script>
import {setToken} from '@/common/utils/auth'
import util from '@/common/utils/util.js'
import {login,auth,getUserInfo,callBack,sms,verify} from '@/api/login'

export default {
  name: "login",
  data() {
     var checkPhone = (rule, value, callback) => {
      const reg = /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/
        if ( reg.test(this.phoneLoginData.phone) ) {
              return callback();
        }
        callback('请输入合法的手机号');
      };
    return {
      loginFlag:true,
      dingLoginFlag:false,
      wxLoginFlag:false,
      phoneFlag:false,
      loginErrMsg:"",
      loginData: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, message:"请输入用户名", trigger: 'blur'}],
        password: [{ required: true, min:6, message:"密码不能少于6个字符", trigger: 'blur'}]
      },
      phoneRules: {
        phone: [{validator: checkPhone, required: true, trigger: 'blur' } ],
        phoneCode:[{required: true, message: '请输入验证码', trigger: 'blur' } ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
       appid: "ding9iaslqxr1ysxutk7",//自己申请的appid
      //appsecret:"JLbkaAgYUogzedomdWQfQVa-zT3L0eYODgHfKcl-cW3NZE1zuUd1qyt4j0suTtSD",//自己申请的appsecret
      redirectUrl: "http://tms.cvci.cn/#/login",//这里是扫码成功后跳转的回调地址
      dingCodeConfig: {
        id: "login_container",//匹配到设置的html的id
        style: "border:none;background-color:#FFFFFF;",
        width: "100%",
        height: "450",
      },//生成二维码样式的配置
      wxLoginInfo:{
          appid: 'wxff16fba48df193a2', // 公众号appid wx*******
          scope: 'snsapi_login', // 网页默认即可
          redirect_uri: encodeURIComponent('https://tms.cvci.cn/#/loginSuccess'), // 授权成功后回调的
          state: 'wxLogin', // 可设置为简单的随机数加session用来校验
      },
      phoneLoginData: {
        phone: '',
        phoneCode: ''
      },
      phoneLoading:false,
      dialogVisible: false,     // 对话框显示和隐藏
      valiBtn:'获取验证码',
      disabled:false,
      userInfo:{

      }
    }
  },
  computed: {
    getRedirectUrl() {
      return encodeURIComponent(this.redirectUrl);
    },
    getAuthUrl() {
      return `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.getRedirectUrl}`;
      //return `https:/login.dingtalk.com/oauth2/auth?redirect_uri=${this.getRedirectUrl}&response_type=code&client_id=${this.appid}&scope=openid&state=STATE&prompt=consent&`;
    },
    getGoto() {
      return encodeURIComponent(this.getAuthUrl);
    },
    getDingCodeConfig() {
      return { ...this.dingCodeConfig, goto: this.getGoto };
    },
  },
  created() {
  	// 初始化钉钉的二维码加载
    this.initDingJs();
    console.log("created方法")
  },
  show(){
    console.log("show方法")
  },
  mounted() {
    console.log("mounted方法")
    if(util.isLogin()){
      this.$router.replace("/index");
    }else{
      if (this.$route.query.code) {

            //loading.close();
        let code = this.$route.query.code
        let state = this.$route.query.state
        if(state == 'wxLogin'){
          console.log("微信扫码登录成功后请求后返回的code：" + code)
          this.getUserInfo(code,state)
        }else{
           let loading = this.$loading({
              lock: true,
              text: '登陆中，请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
          console.log("钉钉扫码登录成功后请求后返回的code：" + code) //
          if (code !== null) {
            auth({code:code}).then(res => {
              if(res.code == 0) {
                this.loginErrMsg = res.msg;
              }else if(res.code == 1) {
                let data = res.data;
                setToken(data.token);
                util.setCookie("uname", data.uname)
                util.setCookie("cname", data.cname)
                util.setCookie("rname", data.rname)
                this.$router.replace("/index")
              }
              this.loading = false;
              loading.close();
            }).catch(res => {
              this.loading = false;
              loading.close();
            })
          }
        }

      }
       this.addDingListener();
       this.initDingLogin();
    }
  },
  methods: {
    //获取验证码
    //获取验证码 并只验证手机号 是否正确
    getCode(){
        this.$refs['phoneForm'].validateField('phone', (err) =>{
            if(err){
                console.log('未通过')
                return;
            }else{
                console.log('已通过')
                this.tackBtn();   //验证码倒数60秒
                sms({phoneNumber:this.phoneLoginData.phone}).then(res => {
                  if(res.code == 0) {
                    this.$message({showClose: true,message: res.msg,type: 'warning'})
                  }else if(res.code == 1) {
                    this.$message({showClose: true,message: '发送成功',type: 'success'})
                  }
                }).catch(res => {

                })

                }
            })
    },
    tackBtn(){       //验证码倒数60秒
          let time = 60;
          let timer = setInterval(() => {
              if(time == 0){
                  clearInterval(timer);
                  this.valiBtn = '获取验证码';
                  this.disabled = false;
              }else{
                  this.disabled = true;
                  this.valiBtn = time + '秒后重试';
                  time--;
              }
          }, 1000);
    },
    handlePhoneLogin() {  //点击登录 验证手机& 验证码是否符合条件
        this.$refs['phoneForm'].validate((valid) => {    // 为表单绑定验证功能
            if (valid) {
                let data = {
                    phoneNumber:this.phoneLoginData.phone,
                    code:this.phoneLoginData.phoneCode,
                    openId:this.userInfo.token.openId
                }
                verify(data).then(res => {
                  if(res.code == 0) {
                    this.$message({showClose: true,message: res.msg,type: 'warning'})
                  }else if(res.code == 1) {
                    this.successLogin(res.data)
                  }
                }).catch(res => {

                })
              } else {
                this.dialogVisible = true;
                return false;
            }
        });
    },
    successLogin(data){
       this.$message({showClose: true,message: '登录成功',type: 'success'})
      setToken(data.token);
      util.setCookie("uname", data.uname)
      util.setCookie("cname", data.cname)
      util.setCookie("rname", data.rname)
      this.$router.replace("/index")
    },
    getUserInfo(code,state){
      let loading = this.$loading({
            lock: true,
            text: '正在校验，请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
        getUserInfo({code:code,state:state}).then(res => {
            if(res.code == 0) {
              this.loginErrMsg = res.msg;
            }else if(res.code == 1) {
              //第二次授权登录
              if(res.data.uname){
                  this.successLogin(res.data)
              }else{
                //微信授权登录成功后，显示填写手机号界面
                this.userInfo = res.data
                this.phoneFlag = true
                this.loginFlag = false
                this.dingLoginFlag = false
                this.wxLoginFlag = false
              }
            }
            this.loading = false;
            loading.close();
          }).catch(res => {
            this.loading = false;
            loading.close();
          })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleBackLogin() {
      this.userInfo = {}
        this.loginFlag = true
        this.dingLoginFlag = false
        this.wxLoginFlag = false
        this.phoneFlag = false
    },
    handleDingLogin() {

        this.loginFlag = false
        this.dingLoginFlag = true
    },
    handleWxLogin() {
      this.wxLoginFlag =true
      this.loginFlag = false
      this.dingLoginFlag = false
      this.phoneFlag = false
      const obj = new WxLogin({
        self_redirect: false,
        id: 'wxLogin_container', // 需要显示的容器id
        appid: this.wxLoginInfo.appid, // 公众号appid wx*******
        scope: this.wxLoginInfo.scope, // 网页默认即可
        redirect_uri: this.wxLoginInfo.redirect_uri, // 授权成功后回调的
        state: this.wxLoginInfo.state, // 可设置为简单的随机数加session用来校验
        style: 'white', // 提供"black"、"white"可选。二维码的样式
      //  href: 'https://static.zcool.cn/passport4.0/css/wxCode.css?v=0.1' // 外部css文件url，需要https
      })
      //wxLogin();
      //window.open()
      // this.loginFlag = false
      // this.wxLoginFlag = true
    },
    handlePhone(){

      // sms({phoneNumber:13792831626});
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loginErrMsg='';
          this.loading = true;
          login(this.loginData).then(res => {
            if(res.code == 0) {
              this.loginErrMsg = res.msg;
            }else if(res.code == 1) {
              let data = res.data;
              setToken(data.token);
              util.setCookie("uname", data.uname)
              util.setCookie("cname", data.cname)
              util.setCookie("rname", data.rname)
              this.$router.replace("/index")
            }
            this.loading = false;
          }).catch(res => {
            this.loading = false;
          })
        } else {
          return false;
        }
      })

    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    initDingLogin() {
      window.DDLogin(this.getDingCodeConfig);
    },
    initDingJs() {
      !(function (window, document) {
        function d(a) {
          var e,
            c = document.createElement("iframe"),
            d = "https://login.dingtalk.com/login/qrcode.htm?goto=" + a.goto;
          (d += a.style ? "&style=" + encodeURIComponent(a.style) : ""),
            (d += a.href ? "&href=" + a.href : ""),
            (c.src = d),
            (c.frameBorder = "0"),
            (c.allowTransparency = "true"),
            (c.scrolling = "no"),
            (c.width = a.width ? a.width + "px" : "400px"),
            (c.height = a.height ? a.height + "px" : "400px"),
            (e = document.getElementById(a.id)),
            (e.innerHTML = ""),
            e.appendChild(c);
        }
        window.DDLogin = d;
      })(window, document);
    },
    addDingListener() {
      let self = this;
      let handleLoginTmpCode = (loginTmpCode) => {
        window.location.href =
          self.getAuthUrl + `&loginTmpCode=${loginTmpCode}`;
      };
      let handleMessage = (event) => {
        if (event.origin == "https://login.dingtalk.com") {
          handleLoginTmpCode(event.data);
        }
      };

      if (typeof window.addEventListener != "undefined") {
        window.addEventListener("message", handleMessage, false);
      } else if (typeof window.attachEvent != "undefined") {
        window.attachEvent("onmessage", handleMessage);
      }
    },
  }

}
</script>

<style lang="scss" >
$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 450px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container{
    padding: 6px 0px 6px 15px;
    color: $dark_gray;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

}
</style>
